package com.ethan.simplesms.service.impl;

import com.ethan.simplesms.component.SmsComponent;
import com.ethan.simplesms.constant.Constant;
import com.ethan.simplesms.service.SendService;
import com.ethan.simplesms.untils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author ethan
 * @CreateDate: 2022/05/29 上午8:24
 * @UpdateDate: 2022/05/29 上午8:24
 * @Version 1.0
 */
@Service
@Slf4j
public class SendServiceImpl implements SendService {
    @Autowired
    SmsComponent smsComponent;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public R send(String to) {
        String cacheKey =String.format(Constant.SMS_LOGIN_KEY,to);
        String cacheCode = redisTemplate.opsForValue().get(cacheKey);
        if (cacheCode!=null&&!StringUtils.isNotBlank(cacheCode)){
            String ttl =  cacheCode.split("_")[1];
            Long time = System.currentTimeMillis()-Long.parseLong(ttl);
            if (time>60*1000){
                return R.error(2,"请稍后再发");
            }
        }
        //这里默认验证码为6666
        String code = "6666";
        String codeValue = code+"_"+System.currentTimeMillis();
        //模拟发送短信
        smsComponent.send(to,code);
        //验证码有效期10分钟有效
        redisTemplate.opsForValue().set(cacheKey,codeValue,10*60*1000, TimeUnit.MILLISECONDS);
        return R.success("");
    }
}
